<template>
    <div class="box">
        <el-card class="card">
            <el-form :inline="true" class="form">
                <el-form-item label="用户名">
                    <el-input @keyup.enter.native="search" v-model="searchValue" placeholder="请输入用户名"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="search" :disabled="searchValue ? false : true">搜索</el-button>
                    <el-button @click="reset" :disabled="searchValue ? false : true">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <el-card>
            <el-button type="primary" @click="add">添加</el-button>
            <el-button type="danger" @click="delbath" :disabled="ids.length ? false : true">批量删除</el-button>
            <el-table :data="tableData" @selection-change="selectChange" border stripe style="margin: 10px 0;">
                <el-table-column type="selection" width="80" align="center"></el-table-column>
                <el-table-column type="index" label="序号" width="80" align="center"></el-table-column>
                <el-table-column prop="id" label="id" width="80" align="center"></el-table-column>
                <el-table-column prop="username" label="用户账号" align="center" show-overflow-tooltip></el-table-column>
                <el-table-column prop="name" label="用户昵称" align="center" show-overflow-tooltip></el-table-column>
                <el-table-column prop="roleName" label="用户角色" align="center" show-overflow-tooltip></el-table-column>
                <el-table-column prop="createTime" label="创建时间" align="center" show-overflow-tooltip></el-table-column>
                <el-table-column prop="updateTime" label="更新时间" align="center" show-overflow-tooltip></el-table-column>
                <el-table-column label="操作" align="center">
                    <template #="{ row, $index }">
                        <el-button type="warning" title="分配角色" size="small" @click="role(row)" icon="user"></el-button>
                        <el-button type="primary" title="编辑" size="small" @click="edit(row)" icon="edit"></el-button>
                        <el-button type="danger" title="删除" size="small" @click="deleteUser(row)"
                            icon="delete"></el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination v-model:current-page="pageNo" v-model:page-size="limit" :page-sizes="[5, 10, 20, 30, 40]"
                :background="true" layout="prev, pager, next, jumper,->,sizes,total" :total="total"
                @size-change="handleSizeChange" @current-change="load" />

            <el-drawer v-model="drawer" :title="userParams.id ? '更新用户' : '添加用户'">
                <el-form :model="userParams" label-width="80px" :rules="rules" ref="formRef">
                    <el-form-item label="用户账号" prop="username">
                        <el-input v-model="userParams.username" placeholder="请输入用户账号"></el-input>
                    </el-form-item>
                    <el-form-item label="用户昵称" prop="name">
                        <el-input v-model="userParams.name" placeholder="请输入用户昵称"></el-input>
                    </el-form-item>
                    <el-form-item v-if="!userParams.id" label="密码" prop="password">
                        <el-input v-model="userParams.password" placeholder="请输入密码"></el-input>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div style="flex: auto">
                        <el-button @click="cancel">取消</el-button>
                        <el-button type="primary" @click="confirm">确定</el-button>
                    </div>
                </template>
            </el-drawer>

            <el-drawer v-model="drawer1" title="分配角色">
                <el-form label-width="80px">
                    <el-form-item label="用户姓名">
                        <el-input disabled v-model="userParams.username"></el-input>
                    </el-form-item>
                    <el-form-item label="角色列表">
                        <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">
                            全选
                        </el-checkbox>
                        <el-checkbox-group v-model="userRole" @change="handleCheckedUsersChange">
                            <el-checkbox v-for="item in allRole" :key="item.id" :label="item">
                                {{ item.roleName }}
                            </el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div style="flex: auto">
                        <el-button @click="cancel1">取消</el-button>
                        <el-button type="primary" @click="confirm1">确定</el-button>
                    </div>
                </template>
            </el-drawer>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue'
import { reqUsersInfo, reqAddOrUpdateUser, reqAllRole, reqSetUserRole, reqRemoveUser, reqSelectUser } from '@/api/acl/user/index'
import type { UserResponseData, Records, User, AllRole, AllRoleResponseData, SetRoleData } from '@/api/acl/user/type'
import { ElMessage, ElMessageBox } from 'element-plus'

let pageNo = ref<number>(1)
let limit = ref<number>(5)
let total = ref<number>(0)
let tableData = ref<Records>([])
let drawer = ref<boolean>(false)
let drawer1 = ref<boolean>(false)
let userParams = reactive<User>({
    username: '',
    password: '',
    name: ''
})
let formRef = ref<any>()
let checkAll = ref<boolean>(false)
let isIndeterminate = ref<boolean>(true)
let allRole = ref<AllRole>([])
let userRole = ref<AllRole>([])
let ids = ref<User[]>([])
let searchValue = ref<string>('')

const validatorUserName = (rule: any, value: any, callBack: any) => {
    if (value.length >= 5 && value.length <= 10) {
        callBack();//校验通过
    } else {
        callBack(new Error("用户名为5到10个字符"));//校验失败
    }
}
//校验用户昵称
const validatorName = (rule: any, value: any, callBack: any) => {
    if (value.trim().length >= 5) {
        callBack()
    } else {
        callBack(new Error('用户昵称至少五位'))
    }
}
//校验密码
const validatorPassword = (rule: any, value: any, callBack: any) => {
    if (value.length >= 5 && value.length <= 15) {
        callBack();//校验通过
    } else {
        callBack(new Error("密码为5到15个字符"));//校验失败
    }
}

const rules = {
    username: [{ required: true, trigger: 'blur', validator: validatorUserName }],
    name: [{ required: true, trigger: 'blur', validator: validatorName }],
    password: [{ required: true, trigger: 'blur', validator: validatorPassword }],
}

onMounted(() => {
    load()
})

const load = async (page = 1) => {
    //当前页码
    pageNo.value = page;
    let result: UserResponseData = await reqUsersInfo(pageNo.value, limit.value, searchValue.value)
    if (result.code == 200) {
        total.value = result.data.total
        tableData.value = result.data.records
    }
}
const confirm = async () => {
    await formRef.value.validate()

    let res: any = await reqAddOrUpdateUser(userParams)
    if (res.code == 200) {
        ElMessage({
            type: 'success',
            message: userParams.id ? '更新成功' : '添加成功'
        })
        if (userParams.id) {
            window.location.reload()
        }
        drawer.value = false
    } else {
        ElMessage({
            type: 'error',
            message: userParams.id ? '更新失败' : '添加失败'
        })
        drawer.value = false
    }
    load(userParams.id ? pageNo.value : 1)
}
const cancel = () => {
    drawer.value = false
}
const search = () => {
    load()
}
const reset = () => {
    searchValue.value = ''
    load()
}
const add = () => {
    drawer.value = true
    Object.assign(userParams, {
        id: undefined,
        username: '',
        password: '',
        name: ''
    })
    nextTick(() => {
        formRef.value.clearValidate('username')
        formRef.value.clearValidate('name')
        formRef.value.clearValidate('password')
    })
}
const selectChange = (value: any) => {
    ids.value = value
}
const delbath = () => {
    let idsList: any = ids.value.map(item => {
        return item.id
    })

    ElMessageBox.confirm(
        '你确定要删除这些用户数据吗?',
        'Warning',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            let result: any = await reqSelectUser(idsList)
            if (result.code == 200) {
                //删除成功提示信息
                ElMessage({
                    type: 'success',
                    message: '删除成功'
                });
                //再次获取已有的数据
                load(tableData.value.length > ids.value.length ? pageNo.value : pageNo.value - 1)
            } else {
                ElMessage({
                    type: 'error',
                    message: '删除失败'
                })
            }
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消成功',
            })
        })
}
const edit = (row: User) => {
    drawer.value = true
    Object.assign(userParams, row)
    nextTick(() => {
        formRef.value.clearValidate('username')
        formRef.value.clearValidate('name')
    })
}
const role = async (row: User) => {
    drawer1.value = true
    //存储已有的用户信息
    Object.assign(userParams, row);
    let res: AllRoleResponseData = await reqAllRole((userParams.id as number))
    if (res.code == 200) {
        allRole.value = res.data.allRolesList
        userRole.value = res.data.assignRoles
    }
}
const confirm1 = async () => {
    let data: SetRoleData = {
        userId: (userParams.id as number),
        roleIdList: userRole.value.map(item => {
            return (item.id as number)
        })
    }

    let res: any = await reqSetUserRole(data)
    if (res.code == 200) {
        ElMessage({
            type: 'success',
            message: '分配成功'
        })
    } else {
        ElMessage({
            type: 'error',
            message: '分配失败'
        })
    }
    drawer1.value = false
    load(pageNo.value)
}
const cancel1 = () => {
    drawer1.value = false
}
const deleteUser = async (row: User) => {
    ElMessageBox.confirm(
        `你确定要删除用户${row.username}吗?`,
        'Warning',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            let result = await reqRemoveUser((row.id as number))
            if (result.code == 200) {
                //删除成功提示信息
                ElMessage({
                    type: 'success',
                    message: '删除成功'
                });
                //再次获取已有的数据
                load(tableData.value.length > 1 ? pageNo.value : pageNo.value - 1)
            } else {
                ElMessage({
                    type: 'error',
                    message: '删除失败'
                })
            }
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消成功',
            })
        })
}
const handleSizeChange = () => {
    load()
}
const handleCheckAllChange = (val: boolean) => {
    userRole.value = val ? allRole.value : []
    isIndeterminate.value = false
}
const handleCheckedUsersChange = (value: string[]) => {
    const checkedCount = value.length
    checkAll.value = checkedCount === allRole.value.length
    isIndeterminate.value = checkedCount > 0 && checkedCount < allRole.value.length
}
</script>

<style scoped lang="scss">
.form {
    display: flex;
    justify-content: space-between;
}

.card {
    height: 80px;
    margin-bottom: 10px;
}
</style>